package org.example.server.service.impl;

import org.example.dto.DepartmentDTO;
import org.example.dto.OrgInfoDTO;
import org.example.entity.Department;
import org.example.entity.OrgInfo;
import org.example.server.mapper.DepartmentMapper;
import org.example.server.mapper.OrgInfoMapper;
import org.example.server.service.DepartmentService;

import org.example.vo.ChildrenVO;
import org.example.vo.DepartmentVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service

public class DepartmentServiceImpl implements DepartmentService {


    private static final Logger log = LoggerFactory.getLogger(DepartmentServiceImpl.class);
    @Resource
    private OrgInfoMapper orgInfoMapper;
    @Resource
    private DepartmentMapper departmentMapper;


    @Override
    public List<DepartmentVO> select(String hospitalNo) {


        OrgInfo orgInfo = orgInfoMapper.selectByNo(hospitalNo);

        List<Department> departmentList = departmentMapper.select(hospitalNo);


        List<DepartmentVO> departmentVOList = new ArrayList<>();
        departmentList.forEach(department -> {

            if (department.getParentDeptCode() != null) {
                String parentDeptCode = department.getParentDeptCode();
                departmentList.forEach(department1 -> {
                    List<ChildrenVO> children = new ArrayList<>();
                    if (department1.getDeptCode().equals(parentDeptCode)) {
                        ChildrenVO departmentVO2 = ChildrenVO.builder().
                                hospitalNo(hospitalNo).
                                hospitalName(orgInfo.getHospitalName()).
                                deptCode(department.getDeptCode()).
                                deptName(department.getDepartmentName()).
                                parentDeptCode(department1.getDeptCode()).
                                parentDeptName(department1.getDepartmentName()).
                                deptAddr(department.getDeptAddress()).build();
                        children.add(departmentVO2);


                        DepartmentVO departmentVO = DepartmentVO.builder().
                                hospitalNo(hospitalNo).
                                hospitalName(orgInfo.getHospitalName()).
                                deptCode(department1.getDeptCode()).
                                deptName(department1.getDepartmentName()).
                                parentDeptCode("").
                                parentDeptName("").
                                deptAddr(department1.getDeptAddress()).
                                children(children).build();
                        departmentVOList.add(departmentVO);
                    }
                });


            }
        });
        return departmentVOList;

    }
}
